package org.suze.springboot.base.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.suze.springboot.base.model.BaseModel;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Date : 上午11:52 2017/9/11
 * @Author : 石冬冬-Heil Hitler(dongdong.shi@mljr.com)
 */
public abstract class RedisHashServiceImpl<T extends BaseModel> {
    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    protected HashOperations<String, String, T> hashOperations;

    /**
     * 存入redis中的key
     *
     * @return
     */
    protected abstract String getRedisKey();


    
    public List getAll() {
        return hashOperations.values(getRedisKey());
    }

    
    public Set<String> getKeys() {
        return hashOperations.keys(getRedisKey());
    }

    
    public void put(String key, Object domain, long expire) {
        this.put(key,domain,expire,TimeUnit.SECONDS);
    }

    
    public void put(Object domain, long expire) {
        this.put(this.getRedisKey(),domain,expire,TimeUnit.SECONDS);
    }

    
    public void put(String key, Object domain, long expire, TimeUnit unit) {
        BaseModel model = (BaseModel)domain;
        hashOperations.put(key, model.getKey(), (T)model);
        if (expire != -1) {
            redisTemplate.expire(model.getKey(), expire, unit);
        }
    }

    
    public void put(Object domain, long expire, TimeUnit unit) {
        this.put(this.getRedisKey(),domain,expire,unit);
    }

    
    public void remove(String key) {
        hashOperations.delete(getRedisKey(), key);
    }

    
    public Object get(String key) {
        return hashOperations.get(getRedisKey(), key);
    }
}
